using System.Linq;

namespace Test.ConsoleProgram.Algorithm.Interview
{
    [TestDescription("面试题 16.18. 模式匹配")]
    public class No00160018_PatternMatching : AbsBaseTestItem
    {
        /*
        提示：

            0 <= len(pattern) <= 1000
            0 <= len(value) <= 1000
            你可以假设pattern只包含字母"a"和"b"，value仅包含小写字母。
        */

        public override void OnTest()
        {
            Assert.TestExe(PatternMatching, "", "", true);
            Assert.TestExe(PatternMatching, "", "x", false);
            Assert.TestExe(PatternMatching, "a", "", true);
            Assert.TestExe(PatternMatching, "ab", "", false);
            Assert.TestExe(PatternMatching, "abba", "dogcatcatdog", true);
            Assert.TestExe(PatternMatching, "abba", "dogcatcatfish", false);
            Assert.TestExe(PatternMatching, "aaaa", "dogcatcatdog", false);
            Assert.TestExe(PatternMatching, "abba", "dogdogdogdog", true);
            Assert.TestExe(PatternMatching, "bbbaa", "xxxxxxy", false);
            Assert.TestExe(PatternMatching, "bbbaa", "xxxxxx", true);
        }

        public bool PatternMatching(string pattern, string value)
        {
            if (string.IsNullOrEmpty(pattern) && string.IsNullOrEmpty(value)) return true;
            if (string.IsNullOrEmpty(pattern)) return false;
            if (pattern.Length == 1 && string.IsNullOrEmpty(value)) return true;
            if (pattern.Length == 2 && string.IsNullOrEmpty(value)) return false;
            int plen = pattern.Length;
            string[] patternReStrArrs = new string[plen];
            var dic = new System.Collections.Generic.Dictionary<char, int>() { };
            for (int i = 0; i < plen; i++)
            {
                char c = pattern[i];
                if (!dic.ContainsKey(c))
                {
                    dic[c] = dic.Count() + 1;
                    patternReStrArrs[i] = @"(\w*)";
                    continue;
                }
                patternReStrArrs[i] = $"\\{dic[c]}";
            }
            string patternReStr = "^" + string.Join("", patternReStrArrs) + "$";
            var match = System.Text.RegularExpressions.Regex.Match(value, patternReStr);
            return match.Success && match.Groups[1] != match.Groups[2];
        }
    }
}
